package cn.iune.erp.accounting;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.DataUtils;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.common.base.BaseJPAImpl;



@Repository
public class PeriodCaptionDaoJPAImpl extends BaseJPAImpl<PeriodCaption> implements IPeriodCaptionDao {


	private String kSql;
	
//	@PersistenceContext 
//	private EntityManager em ;

	@Override
	public void insert(PeriodCaption obj) {
		em.persist(obj);
	}

	@Override
	public void delete(String fID) {
		em.remove(em.getReference(PeriodCaption.class, fID));
	}

	@Override
	public PeriodCaption update(PeriodCaption obj) {
		PeriodCaption objNew = em.merge(obj);
		return objNew;
	}

	@Override
	public PeriodCaption getByID(String fID) {
		PeriodCaption singleResult = em.find(PeriodCaption.class, fID);
		return singleResult;
	}

	@Override
	public List<PeriodCaption> getAll() {
		kSql="SELECT PeriodCaption FROM PeriodCaption PeriodCaption ";
		Query query = em.createQuery(kSql);
		@SuppressWarnings("unchecked")
		List<PeriodCaption> resultList = query.getResultList();
		return resultList;
	}


	@Override
	public List<PeriodCaption> getByPeriod(String yearNo, String periodNo, String enterpriseNo) {
		kSql="SELECT PeriodCaption FROM PeriodCaption PeriodCaption "
				+ " WHERE ( PeriodCaption.periodNo = :periodNo ) "
				+ " AND ( PeriodCaption.yearNo = :yearNo ) "
				+ " AND ( PeriodCaption.enterpriseNo = :enterpriseNo ) "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("periodNo", periodNo);
		query.setParameter("yearNo", yearNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<PeriodCaption> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public int deleteByPeriod(String yearNo, String periodNo, String enterpriseNo) {
		kSql="DELETE FROM PeriodCaption PeriodCaption "
			+ " WHERE ( PeriodCaption.periodNo = :periodNo ) "
			+ " AND ( PeriodCaption.yearNo = :yearNo ) "
			+ " AND ( PeriodCaption.enterpriseNo = :enterpriseNo ) "
			;		
		Query query = em.createQuery(kSql);
		query.setParameter("periodNo", periodNo);
		query.setParameter("yearNo", yearNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		int result = query.executeUpdate();
		return result;
	}

	
	
	
	
	

	@Override
	public PeriodCaption getByNo(String yearNo, String periodNo, String captionNo, String enterpriseNo) {
		//1、定义sql语句
		kSql="SELECT PeriodCaption FROM PeriodCaption PeriodCaption "
				+ " WHERE ( PeriodCaption.captionNo = :captionNo ) "
				+ " AND ( PeriodCaption.yearNo = :yearNo ) "
				+ " AND ( PeriodCaption.periodNo = :periodNo ) "
				+ " AND ( PeriodCaption.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("captionNo", captionNo);
		query.setParameter("yearNo", yearNo);
		query.setParameter("periodNo", periodNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		PeriodCaption singleResult = null;
		try{
			singleResult = (PeriodCaption) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}
	
	@Override
	public JSONObject create(JSONObject data) {
		//缺省列
		String defColstr = Utils.getDefCols(PeriodCaption.class);
		data.put("defColstr", defColstr);
		return Utils.newData(data);

	}

	@Override
	public JSONObject query(JSONObject data) throws SQLException{
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");

		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT ShopCart FROM ShopCart ShopCart %s %s ";
		String select = "PeriodCaption.*"
				//截取第2个‘/’之前的所有字符，然后再截取第1个‘/’之后的所有字符（从右向左数）
//				+ ",substring_index(substring_index(PeriodCaption.fAddress,'/',2),'/',-1) as fRegion"
//				+ ",substring_index(substring_index(PeriodCaption.fAddress,'/',3),'/',-1) as fProvince"
//				+ ",substring_index(substring_index(PeriodCaption.fAddress,'/',4),'/',-1) as fCity"
//				+ ",substring_index(PeriodCaption.fAddress,'/',-1) as fZone"
				;
		String from = "PeriodCaption PeriodCaption";

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("captionNo LIKE ? OR captionName LIKE ? OR comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 3; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("PeriodCaption.fID='"+id+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
				filters.add(jsonFilter.getString("filter"));
			}
		}
	
		
		String where = "";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		//System.out.println(this.getClass().getName()+".query.sql-->>"+sql);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn;
		conn = super.getConnection();
		/////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////
		//这个经过测试是失败的
//		em.getTransaction().begin();
//		Connection conn = em.unwrap(java.sql.Connection.class);
		/////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////
		
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT ShopCart.fID FROM ShopCart ShopCart    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);
		/////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////
//		em.getTransaction().commit();
		/////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////
		//关闭连接
		conn.close();

		table.setTotal(Integer.parseInt(total.toString()));
		table.setOffset(offset);
		table.setTableName("PeriodCaption");
		
		JSONObject json = Transform.tableToJson(table);

		return json;
	}


	
}
